<template>
  <div class="admin-login-page">
    <div class="login-container">
      <!-- Logo和标题 -->
      <div class="title-bar">
        <img src="../../../assets/coffee_logo.png" alt="logo" class="logo">
      </div>
      <h1 class="login-title">管理端登录</h1>

      <!-- 登录表单 -->
      <a-form
        :model="formState"
        name="admin-login"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <!-- 手机号 -->
        <a-form-item
          label="手机号"
          name="phone"
          :rules="[
            { required: true, message: '请输入手机号' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
          ]"
        >
          <div class="input-group">
            <a-input
              v-model:value="formState.phone"
              placeholder="请输入手机号"
            />
          </div>
        </a-form-item>

        <!-- 验证码 -->
        <a-form-item
          label="验证码"
          name="verifyCode"
          :rules="[{ required: true, message: '请输入验证码' }]"
        >
          <div class="input-group">
            <a-input
              v-model:value="formState.verifyCode"
              placeholder="请输入验证码"
            />
            <a-button
              :disabled="countdown > 0"
              @click="handleGetCode"
              class="verify-button"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
            </a-button>
          </div>
        </a-form-item>

        <!-- 登录按钮 -->
        <a-form-item :wrapper-col="{ offset: 6, span: 18 }">
          <a-button
            type="primary"
            html-type="submit"
            class="login-button"
            :loading="loading"
          >
            登录
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { userLogin } from "@/api/user";
import { message, Modal } from "ant-design-vue";
import { useRouter } from "vue-router";
import { getVerificationCode } from "@/api/sms";
import {useAdminLoginStore} from "@/store/useAdminLoginUserStore";

const router = useRouter();
const loginStore = useAdminLoginStore();
const countdown = ref(0);
const loading = ref(false);

interface FormState {
  phone: string;
  verifyCode: string;
}

const formState = reactive<FormState>({
  phone: '',
  verifyCode: '',
});

// 获取验证码
const handleGetCode = async () => {
  if (!formState.phone) {
    message.error('请先输入手机号');
    return;
  }
  if (!/^1[3-9]\d{9}$/.test(formState.phone)) {
    message.error('请输入正确的手机号');
    return;
  }

  try {
    const res = await getVerificationCode(formState.phone);
    if (res.data.code === 200 && res.data.data) {
      Modal.success({
        title: '验证码',
        content: `您的验证码是：${res.data.data.code}`,
        okText: '我知道了'
      });
      countdown.value = 60;
      const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      message.error(res.data.msg || '获取验证码失败');
    }
  } catch (error) {
    message.error('获取验证码失败');
  }
};

// 处理登录
const onFinish = async (values: FormState) => {
  loading.value = true;
  try {
    const loginParams = {
      phone: values.phone,
      verifyCode: Number(values.verifyCode)
    };

    const res = await userLogin(loginParams);
    if (res.data.code === 200 && res.data.data) {
      const token = res.data.data.token;
      console.log(token);
      localStorage.setItem('adminToken', res.data.data.token);
      message.success("登录成功");
      console.log('测试token：' + localStorage.getItem('adminToken'));


      try {
        // 存储管理员信息
        await loginStore.fetchAdminLoginUser();
        // 跳转到管理端首页
        router.push('/admin/adminHome');
      } catch (error) {
        console.error('获取用户信息失败:', error);
        message.error("获取用户信息失败，请刷新页面重试");
      }
    } else {
      message.error(res.data.msg || "登录失败");
    }
  } catch (error) {
    console.error('登录失败:', error);
    message.error("登录失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};
</script>

<style scoped>
.admin-login-page {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
}

.login-container {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.title-bar {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
}

.logo {
  height: 48px;
}

.login-title {
  text-align: center;
  margin-bottom: 40px;
  font-size: 24px;
  font-weight: 500;
  color: #333;
}

.input-group {
  display: flex;
  gap: 8px;
}

.verify-button {
  white-space: nowrap;
}

.login-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
}
</style>
